package july.framework.exsolver.reader;


import com.alibaba.fastjson.JSON;
import july.framework.exsolver.bean.ExCell;
import july.framework.exsolver.bean.ExRow;
import lombok.Data;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Data
public class ExcelReader {

    // 保存读取到的book内容
    private XSSFWorkbook workbook;
    private Map<String, List<ExRow>> sheetMap= new HashMap<>();

    public ExcelReader(String fileName) throws IOException {

        File xlsFile = new File(fileName);
        /**
         * 这里根据不同的excel类型
         * 可以选取不同的处理类：
         *          1.XSSFWorkbook
         *          2.HSSFWorkbook
         */
        // 获得工作簿
        this.workbook = new XSSFWorkbook(new FileInputStream(xlsFile));

        // 获得工作表
        int sheetNum = workbook.getNumberOfSheets();
        for (int i = 0; i < sheetNum; i++) {

            List<ExRow> rows = new ArrayList<>();

            XSSFSheet sheet = workbook.getSheetAt(i);

            for (Row sheetRow : sheet) {

                // 获取第i行数据
                List<ExCell> cellValue = new ArrayList<>();

                for (Cell cell : sheetRow) {

                    // 获取第0格数据
                    ExCell exCell = new ExCell();
                    exCell.setCellNum(cell.getColumnIndex());
                    exCell.setValue(cell.toString());
                    cellValue.add(exCell);
                }

                ExRow row = new ExRow();
                row.setRowNum(sheetRow.getRowNum());
                row.setCells(cellValue);

                rows.add(row);
            }

            String sheetName = sheet.getSheetName();
            sheetMap.put(sheetName,rows);
        }

        //System.out.println(JSON.toJSONString(sheetMap));

    }
}